import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import { set_user_token, get_user_token } from '@/utils/storage';
import { user_detail } from '@/api/user';
import { userDetail } from '@/api/common';
import { useUserStore } from '@/store/user';

const Home = () => import('@/views/Home.vue');
const Category = () => import('@/views/Category.vue');
const Global = () => import('@/views/Global.vue');
// const Selection = () => import('@/views/Selection.vue');
const Settings = () => import('@/views/Settings.vue');

const routes: Array<RouteRecordRaw> = [
  {
    name: 'home',
    path: '/',
    component: Home,
    redirect: { name: 'category' },
    children: [
      { name: 'category', path: '/category', component: Category },
      {
        name: 'selection',
        path: '/selection',
        component: () => import('@/views/Selection/index.vue'),
      },
      {
        name: 'customCreate',
        path: '/custom-create',
        component: () => import('@/views/CustomCreate.vue'),
      },
      { name: 'setting', path: '/settings', component: Settings },
      { name: 'global', path: '/global', component: Global },
      {
        name: 'split',
        path: '/split',
        component: () => import('@/views/Split/index.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue'),
  },
];

const whiteList = ['/login'];

const router = createRouter({
  // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
  history: createWebHashHistory(),
  routes, // short for `routes: routes`
});

const defaultTitle = '一刀云·类目管理系统';
router.beforeEach(async (to, _from, next) => {
  const title = to.meta.title || defaultTitle;
  document.title = String(title);
  const token = get_user_token();
  if (token) {
    const userStore = useUserStore();
    const userInfo = userStore.currentUser;
    if (userInfo) {
      next();
    } else {
      if (to.name == 'login') {
        next();
      } else {
        const res = await userDetail();
        userStore.setCurrentUser(res.data);
        st.set('user_info', res.data);
        next();
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({ path: '/login' });
    }
  }
});

const init = () => {
  const url = new URL(window.location.href);
  // token一定要在#前面
  const token = url.searchParams.get('token');
  if (!!token) {
    set_user_token(token);
    url.searchParams.delete('token');
    window.location.href = url.toString();
  }
};

init();

export default router;
